package com.lzymall.service.impl;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.lzymall.common.Const;
import com.lzymall.common.ResponseCode;
import com.lzymall.common.ServiceResponse;
import com.lzymall.dao.CartMapper;
import com.lzymall.dao.ProductMapper;
import com.lzymall.pojo.Cart;
import com.lzymall.pojo.Product;
import com.lzymall.service.ICartService;
import com.lzymall.util.BigDecimalUtil;
import com.lzymall.util.PropertiesUtil;
import com.lzymall.vo.CartProductVo;
import com.lzymall.vo.CartVo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.beans.IntrospectionException;
import java.math.BigDecimal;
import java.util.List;



/**
 * @Author: lizhenyao
 * @Desciption:
 */
@Service("iCartService")
public class CartServiceImpl implements ICartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;

    public ServiceResponse<CartVo> add(Integer userId, Integer count, Integer productId){
        if (count == null || productId == null){
            return ServiceResponse.createByErrorMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Cart cart = cartMapper.selectCartByUserIdProductid(userId, productId);
        if (cart == null){
            //添加一个新的Cart
            Cart insertCart = new Cart();
            insertCart.setUserId(userId);
            insertCart.setProductId(productId);
            insertCart.setQuantity(count);
            insertCart.setChecked(Const.Cart.CHECKED);
            cartMapper.insertSelective(insertCart);
        }else {
            //已经存在了,则在原来的基础上加上count
            cart.setQuantity(cart.getQuantity() + count);
            cartMapper.updateByPrimaryKeySelective(cart);
        }
        return this.list(userId);
    }

    @Override
    public ServiceResponse<CartVo> update(Integer userId, Integer count, Integer productId) {
        if (count == null || productId == null){
            return ServiceResponse.createByErrorMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        //更新对象
        Cart cart = cartMapper.selectCartByUserIdProductid(userId, productId);
        if (cart != null){
            cart.setQuantity(count);
        }
        cartMapper.updateByPrimaryKeySelective(cart);
        return this.list(userId);
    }

    @Override
    public ServiceResponse<CartVo> deleteProduct(Integer userId, String productIds) {
        List<String> productList = Splitter.on(",").splitToList(productIds);
        if(CollectionUtils.isEmpty(productList)){
            return ServiceResponse.createByErrorMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        cartMapper.deleteByUserIdProductIds(userId, productList);
        return this.list(userId);
    }

    @Override
    public ServiceResponse<CartVo> list(Integer id) {
        CartVo cartVo = getCartVoLimit(id);
        return ServiceResponse.createBySuccess(cartVo);
    }

    public ServiceResponse<CartVo> selectOrUnSelectAll(Integer userId, Integer productId, Integer checked){
        cartMapper.checkedOrUncheckedProduct(userId, checked, productId);
        return this.list(userId);
    }

    public ServiceResponse<Integer> getCartProductCount(Integer userId){
        if (userId == 0){
            return ServiceResponse.createBySuccess(0);
        }
        return ServiceResponse.createBySuccess(cartMapper.selectCartProductCount(userId));

    }

    /**
     * 由userId获取到购物车的vo
     * @param userId
     * @return
     */
    private CartVo getCartVoLimit(Integer userId){
        CartVo vo = new CartVo();
        List<Cart> cartList = cartMapper.selectCartByUserId(userId);
        List<CartProductVo> cartProductVoList = Lists.newArrayList();

        //初始化总价格
        BigDecimal cartTotalPrice = new BigDecimal("0");
        if (CollectionUtils.isNotEmpty(cartList)){
            for (Cart item : cartList){
                CartProductVo cartProductVo = new CartProductVo();
                cartProductVo.setId(item.getId());
                cartProductVo.setUserId(item.getUserId());
                cartProductVo.setProductId(item.getProductId());
                cartProductVo.setProductChecked(item.getChecked());
                //获取到所需要的product实体
                Product product = productMapper.selectByPrimaryKey(item.getProductId());
                if (product != null) {
                    cartProductVo.setProductMainImage(product.getMainImage());
                    cartProductVo.setProductName(product.getName());
                    cartProductVo.setProductPrice(product.getPrice());
                    cartProductVo.setProductStatus(product.getStatus());
                    cartProductVo.setProductSubtitle(product.getSubtitle());

                    //判断库存
                    int buyLimitCount = 0;
                    if (product.getStock() >= item.getQuantity()){
                        //库存大于商品下单数
                        cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_SUCCESS);
                        buyLimitCount = item.getQuantity();
                    }else {
                        cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_FAIL);
                        buyLimitCount = product.getStock();
                        //更新Cart中的数量
                        Cart newCart = new Cart();
                        newCart.setId(item.getId());
                        newCart.setQuantity(product.getStock());
                        cartMapper.updateByPrimaryKeySelective(newCart);
                    }
                    cartProductVo.setQuantity(buyLimitCount);
                    //计算总价
                    cartProductVo.setProductTotalPrice(BigDecimalUtil.mul(product.getPrice().doubleValue(), cartProductVo.getQuantity()));
                }
                //计算购物车中已选的总价
                if (cartProductVo.getProductChecked() == Const.Cart.CHECKED){
                    cartTotalPrice = BigDecimalUtil.add(cartTotalPrice.doubleValue(), cartProductVo.getProductTotalPrice().doubleValue());
                }
                cartProductVoList.add(cartProductVo);
            }
        }
        vo.setCartProductVoList(cartProductVoList);
        vo.setCartTotalPrice(cartTotalPrice);
        vo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));
        vo.setAllChecked(getAllCheckedStatus(userId));
        return vo;
    }

    private boolean getAllCheckedStatus(Integer userId){
        if (userId == null){
            return false;
        }
        return cartMapper.selectCartProductCheckedStatusByUserId(userId) == 0?true:false;
    }
}
